package com.jinzecloud.reportapproval.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jinzecloud.reportapproval.bean.TestsSummaryTable;
import com.jinzecloud.reportapproval.dto.AdminDto;
import com.jinzecloud.reportapproval.dto.AuditParam;
import com.jinzecloud.reportapproval.dto.DataStagingParam;
import com.jinzecloud.reportapproval.enums.AuditRoleEnums;
import com.jinzecloud.reportapproval.enums.StateEnum;
import com.jinzecloud.reportapproval.enums.TableEnums;
import com.jinzecloud.reportapproval.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.jinzecloud.reportapproval.mapper.UserSurveySummaryMapper;
import com.jinzecloud.reportapproval.bean.UserSurveySummary;
import com.jinzecloud.reportapproval.service.UserSurveySummaryService;

import javax.servlet.http.HttpServletRequest;


@Service("userSurveySummaryService")
public class UserSurveySummaryServiceImpl extends ServiceImpl<UserSurveySummaryMapper, UserSurveySummary> implements UserSurveySummaryService {
    @Autowired
    private FileUploadUtil fileUploadUtil;
    @Autowired
    private HttpServletRequest request;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserSurveySummary> page = this.page(
                new Query<UserSurveySummary>().getPage(params),
                new QueryWrapper<UserSurveySummary>().like("project_num",params.get("key"))
        );
        return new PageUtils(page);
    }

    @Override
    public String createPdf(Integer id) {
        UserSurveySummary userSurveySummary=getById(id);
        JSONObject data=JSONObject.parseObject(JSONObject.toJSONString(userSurveySummary));
        //word
        File tempFile = WordUtil.getWordFile("template/usersurvey.docx", data);
        if (tempFile == null) return null;
        String fileName = "用户调查汇总表";
        String uploadDirectory = fileUploadUtil.getUploadFilePath("temp");
        String filePath = uploadDirectory + userSurveySummary.getProjectNum() + fileName;
        String savePath = RequestUtils.getBasePath(request) + "upload/temp/" + userSurveySummary.getProjectNum() +fileName;
        FileUtil.copy(tempFile, new File(filePath + ".docx"),true);
        PDFUtil.WordToPdf(tempFile, new File(filePath + ".pdf"));

        update(new LambdaUpdateWrapper<UserSurveySummary>().set(UserSurveySummary::getWordPath, savePath + ".docx").set(UserSurveySummary::getPdfPath, savePath + ".pdf").eq(UserSurveySummary::getId, id));

        return RequestUtils.getBasePath(request) + "upload/temp/" + userSurveySummary.getProjectNum() + fileName + ".pdf";
    }

    @Override
    public Object auditList(DataStagingParam param) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LambdaQueryWrapper<UserSurveySummary> queryWrapper = new LambdaQueryWrapper<>();
        List<AdminDto> adminDto = AuditUtil.getAdminDto(authentication.getName());
        Set<Integer> roleSet = adminDto.stream().map(a -> StateEnum.getStateEnumByAuditRole(a.getRoleCode()).getState()).collect(Collectors.toSet());
        roleSet.remove(StateEnum.UN_SUBMIT.getState());
        queryWrapper.in(UserSurveySummary::getAuditStatus, roleSet);
        return page(new Page<>(param.getPageNo(), param.getPageSize()), queryWrapper);
    }

    @Override
    public R audit(AuditParam auditParam) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        List<AdminDto> adminDos = AuditUtil.getAdminDto(authentication.getName());
        if (CollectionUtil.isEmpty(adminDos)) return R.error("您没有审核权限！");
        UserSurveySummary userSurveySummary = this.getById(auditParam.getId());
        int state = Integer.parseInt(userSurveySummary.getAuditStatus());
        if (!auditParam.isState()) {
            userSurveySummary.setAuditStatus(String.valueOf(StateEnum.APPROVAL_NOT_PASS.getState()));
            userSurveySummary.setAuditOpinion(auditParam.getAuditOpinion());
            userSurveySummary.setAuditDate(DateUtil.date().toDateStr());
            updateById(userSurveySummary);
            return R.ok();
        }
        StateEnum currentAuditState = AuditUtil.getStateText(TableEnums.TESTS_SUMMARY_TABLE.getTableName(), state);
        Integer nextAuditStateIndex = AuditUtil.getNextAuditState(TableEnums.TESTS_SUMMARY_TABLE.getTableName(), state, adminDos.stream().map(AdminDto::getRoleCode).toList());
        AdminDto adminDto = adminDos.stream().filter(a -> StrUtil.equals(a.getRoleCode(), currentAuditState.getAuditRole()))
                .findFirst().orElse(null);
        if (adminDto == null || nextAuditStateIndex == null) return R.error("您没有审核权限！");
        if (StrUtil.equals(adminDto.getRoleCode(), AuditRoleEnums.AGGREGATORS.getCode())) userSurveySummary.setSummaryName(adminDto.getAdSignature());
        if (StrUtil.equals(adminDto.getRoleCode(), AuditRoleEnums.CHECKER.getCode())) userSurveySummary.setCheckerName(adminDto.getAdSignature());
        userSurveySummary.setAuditStatus(String.valueOf(nextAuditStateIndex));
        userSurveySummary.setAuditOpinion(auditParam.getAuditOpinion());
        userSurveySummary.setAuditDate(DateUtil.date().toDateStr());
        updateById(userSurveySummary);
        return R.ok();
    }

    @Override
    public JSONObject userSurveySummaryJson(String projectUuid) {
        UserSurveySummary userSurveySummary=getOne(new QueryWrapper<UserSurveySummary>().eq("project_num", projectUuid));
        if (userSurveySummary==null) return null;
        JSONObject data=JSONObject.parseObject(JSONObject.toJSONString(userSurveySummary));

        return data;
    }

    @Override
    public UserSurveySummary getProductNumber(String projectNumber) {
        UserSurveySummary userSurveySummary=getOne(new QueryWrapper<UserSurveySummary>().eq("project_num", projectNumber));
        return userSurveySummary;
    }

}